package com.hoperun.checkcloth.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hoperun.checkcloth.databinding.ItemFlawTypeBinding
import com.hoperun.checkcloth.net.DictItem

class BoltFlawTypeAdapter(private val itemClickListener: ((DictItem) -> Unit)? = null) : RecyclerView.Adapter<BoltFlawTypeVH>() {
    private val names: MutableList<DictItem> = mutableListOf()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BoltFlawTypeVH {
        val binding = ItemFlawTypeBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return BoltFlawTypeVH(binding)
    }

    override fun onBindViewHolder(holder: BoltFlawTypeVH, position: Int) {
        holder.setText(names[position].value)
        holder.itemView.setOnClickListener {
            // 因为有空白的条目，当作分割，所以名字为空的 Item 的点击事件不处理
            names[position].takeIf { it.value.isNotEmpty() }?.let {
                itemClickListener?.apply { invoke(it) }
            }
        }

    }

    override fun getItemCount(): Int = names.size

    fun setDataSet(list: List<DictItem>) {
        names.clear()
        names.addAll(list)
        notifyDataSetChanged()
    }
}


class BoltFlawTypeVH(private val binding: ItemFlawTypeBinding) : RecyclerView.ViewHolder(binding.root) {

    fun setText(text: String) {
        binding.name = text
    }

}
